import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Popconfirm, Select, Cascader } from 'antd';
import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import { transTitle, handleReturnMD5 } from '@/utils/utils';
import FormItem from 'antd/lib/form/FormItem';

import { queryRule, updateRule, addRule, removeRule, queryDefaultRule } from './service';
import styles from '../../../global.less';
const { Option } = Select;
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields, actionRef) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    // message.success('添加成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    // message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param payload
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload);
    hide();
    message.success('修改成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = (props) => {
  const { storeId } = props;
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [formValue, setFormValue] = useState({});
  const [count, setCount] = useState({});
  const actionRef = useRef();
  const formRef = useRef();
  const addFormRef = useRef();
  const handleGetDefaultType = async (payload) => {
    const res = await queryDefaultRule(payload);
    const { data } = res;
    if (payload === 1) {
      addFormRef.current.setFieldsValue({
        consumeScale: data,
      });
    } else {
      addFormRef.current.setFieldsValue({
        rechargeScale: data,
      });
    }
  };
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
    },
    {
      title: '工号',
      dataIndex: 'number',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '工号为必填项',
          },
        ],
      },
    },
    {
      title: 'POS机编号',
      dataIndex: 'posId',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: 'POS机编号为必填项',
          },
        ],
      },
    },
    {
      title: '密码',
      dataIndex: 'password',
      valueType: 'password',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '密码为必填项',
          },
        ],
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" type="password" autoComplete="new-password" />;
      },
    },
    {
      title: '充值比例',
      dataIndex: 'rechargeScale',
      valueType: 'text',
      hideInSearch: true,
      render: (payload) => {
        return <div>{payload}% </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" suffix="%" />;
      },
    },
    {
      title: '消费比例',
      dataIndex: 'consumeScale',
      valueType: 'text',
      hideInSearch: true,
      render: (payload) => {
        return <div>{payload}% </div>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="请输入" suffix="%" />;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              const payload = JSON.parse(JSON.stringify(record));
              delete payload.password;
              setFormValue(payload);
              handleEditModalVisible(true);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a onClick={() => {}}>删除</a>
          </Popconfirm>
          {/* <Divider type="vertical" />
          <a
            onClick={() => {
              // setFormValue(record);
            }}
          >
            设为店长
          </a> */}
        </>
      ),
    },
  ];
  return (
    <div>
      <ProTable
        headerTitle="店长列表"
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        scroll={{x:1200}}
        bordered
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setFormValue({});
              handleGetDefaultType(1);
              handleGetDefaultType(2);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增店长
          </Button>,
        ]}
        options={false}
        beforeSearchSubmit={(payload) => {
          return payload;
        }}
        request={(params, sorter, filter) => {
          params.storeId = storeId;
          return queryRule({ ...params });
        }}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
        // options={false}
      />
      <CreateForm
        title="新增店长"
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.storeId = storeId;
            value.password = handleReturnMD5(value.password);
            const success = await handleAdd(value, actionRef);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          formRef={addFormRef}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改店长"
        onCancel={() => {
          handleEditModalVisible(false);
        }}
        modalVisible={createEditModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.id = formValue.id;
            value.password = handleReturnMD5(value.password);
            const success = await handleUpdate(value, actionRef);
            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      {/* <CreateForm
        onCancel={() => handleStoreMasterModalVisible(false)}
        modalVisible={storeMasterModalVisible}
        width={1400}
        title="街道办位置"
      >
        <MasterList />
      </CreateForm> */}
    </div>
  );
};

export default TableList;
